package cn.schoolwow.quickdao.module.database.dml.instance.flow.common;

import cn.schoolwow.quickdao.domain.entity.Entity;
import cn.schoolwow.quickdao.domain.entity.Property;
import cn.schoolwow.quickdao.module.database.dml.common.domain.ManipulationOption;
import cn.schoolwow.quickdao.module.database.parent.domain.GetStatementSupplier;
import cn.schoolwow.quickdao.module.database.parent.flow.GetAndCacheStatementFlow;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

import java.util.ArrayList;
import java.util.List;

public class SetInstanceStatementFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        Entity entity = (Entity) flowContext.checkData("entity");
        ManipulationOption manipulationOption = flowContext.checkInstanceData(ManipulationOption.class);
        GetStatementSupplier getStatementSupplier = flowContext.checkInstanceData(GetStatementSupplier.class);

        if(manipulationOption.partColumnSet.isEmpty()&&manipulationOption.excludeColumnSet.isEmpty()){
            flowContext.putData("propertyList", entity.properties);
            flowContext.executeFlowList(new GetAndCacheStatementFlow());
            return;
        }

        List<Property> propertyList = new ArrayList<>();
        if(manipulationOption.partColumnSet.isEmpty()){
           propertyList.addAll(entity.properties);
        }else{
            for(Property property:entity.properties){
                if(manipulationOption.partColumnSet.contains(property.column)||manipulationOption.partColumnSet.contains(property.name)){
                    propertyList.add(property);
                }
            }
        }
        if(!manipulationOption.excludeColumnSet.isEmpty()){
            propertyList.removeIf(property -> manipulationOption.excludeColumnSet.contains(property.name) || manipulationOption.excludeColumnSet.contains(property.column));
        }
        flowContext.putData("propertyList", propertyList);
        String sql = getStatementSupplier.getStatement();
        flowContext.putData("sql", sql);
    }

    @Override
    public String name() {
        return "设置插入和更新的SQL语句";
    }

}